const Metalsmith = require('metalsmith');
const Handlebars = require('handlebars');

module.exports = function (meta = {}, src, dest) {
    // 判断src是否为空
    if(!src) reject(new Error('src不能为空!'));
    
    // 返回一个Promise对象
    return new Promise((resolve, reject) => {
        Metalsmith(process.cwd()) //process.cwd()和__dirname的区别
            .metadata(meta)
            .clean(false)
            .source(src)
            .destination(dest)
            .use((files, metalsmith) => {
                const meta = metalsmith.metadata();
                Object.keys(files).forEach(fileName => {
                    
                    let newName = fileName;
                    newName = fileName.replace(/_name/g, meta.name);

                    if (newName !== fileName) {
                        files[newName] = files[fileName];
                        delete files[fileName];
                    }
                })
            })
            .use((files, metalsmith, done) => {
                const meta = metalsmith.metadata();

                Object.keys(files).forEach(fileName => {
                    // 将文件的内容转换为字符串
                    const content = files[fileName].contents.toString();

                    // Buffer.from()创建一个新的数据流
                    // Handlebars.compile(template)(data) 将template中的所有模板遍历并填入对应data中的值
                    files[fileName].contents = Buffer.from(Handlebars.compile(content)(meta));
                });
                done();
            })
            .build((err) => {
                err ? reject(err) : resolve();
            })
    })
}
